/**
 * 图谱渲染器
 * 提供不同类型图谱的专用渲染函数
 */
import * as d3 from 'd3';
import { getGraphTypeStyle, getNodeShapeRenderer } from '../styles/graphThemes';
import { 
  flattenNodeHierarchy, 
  calculateNodeDegrees,
  createDragBehavior
} from './graphLayoutUtils.jsx';
import { buildMindMapHierarchy, calculateMindMapLayout, generateMindMapPath } from './mindMapUtils.jsx';
import { 
  renderConceptMap, 
  renderFlowChart, 
  renderSocialNetwork, 
  renderOntologyGraph 
} from './graphRenderersExtended.jsx';

/**
 * 思维导图专用渲染
 */
export const renderMindMap = (container, nodes, edges, width, height, onNodeClick) => {
  // 获取思维导图样式
  const mindMapStyle = getGraphTypeStyle('mind');
  
  // 如果没有节点，直接返回
  if (!nodes || nodes.length === 0) {
    return [];
  }
  
  console.log('思维导图渲染 - 输入数据:', { nodes: nodes.length, edges: edges.length });
  
  // 使用思维导图层次结构构建函数
  const hierarchyData = buildMindMapHierarchy(nodes, edges);
  
  console.log('思维导图层次结构:', hierarchyData);
  
  if (!hierarchyData.root) {
    console.warn("无法构建思维导图层次结构，使用简单布局");
    // 回退到简单的辐射布局
    const centerX = width / 2;
    const centerY = height / 2;
    const radius = Math.min(width, height) * 0.3;
    
    const layoutedNodes = nodes.map((node, index) => {
      if (index === 0) {
        return { ...node, x: centerX, y: centerY, level: 0 };
      }
      const angle = ((index - 1) / (nodes.length - 1)) * 2 * Math.PI;
      return {
        ...node,
        x: centerX + radius * Math.cos(angle),
        y: centerY + radius * Math.sin(angle),
        level: 1
      };
    });
    
    renderMindMapNodes(container, layoutedNodes, edges, mindMapStyle, onNodeClick);
    return layoutedNodes;
  }
  
  // 使用布局计算函数
  const layoutedNodes = calculateMindMapLayout(hierarchyData, width, height);
  
  console.log('思维导图布局结果:', layoutedNodes);
  
  renderMindMapNodes(container, layoutedNodes, edges, mindMapStyle, onNodeClick);
  return layoutedNodes;
};

/**
 * 渲染思维导图节点和连接线
 */
const renderMindMapNodes = (container, layoutedNodes, edges, mindMapStyle, onNodeClick) => {
  console.log('渲染思维导图节点:', { layoutedNodes: layoutedNodes.length, edges: edges.length });
  
  // 创建连接线
  const links = container.append('g').attr('class', 'mind-links');
  
  // 过滤有效的边（确保源节点和目标节点都存在）
  const validEdges = edges.filter(edge => {
    const sourceId = typeof edge.source === 'object' ? edge.source.id : edge.source;
    const targetId = typeof edge.target === 'object' ? edge.target.id : edge.target;
    const sourceExists = layoutedNodes.some(n => n.id === sourceId);
    const targetExists = layoutedNodes.some(n => n.id === targetId);
    return sourceExists && targetExists;
  });
  
  console.log('有效边数量:', validEdges.length);
  
  validEdges.forEach(edge => {
    const sourceId = typeof edge.source === 'object' ? edge.source.id : edge.source;
    const targetId = typeof edge.target === 'object' ? edge.target.id : edge.target;
    const source = layoutedNodes.find(n => n.id === sourceId);
    const target = layoutedNodes.find(n => n.id === targetId);
    
    if (source && target) {
      // 使用路径生成函数
      const pathData = generateMindMapPath(source, target);
      
      links.append('path')
        .attr('d', pathData)
        .attr('stroke', mindMapStyle.edgeColor({ ...edge, level: source.level || 0 }))
        .attr('stroke-width', mindMapStyle.edgeWidth({ ...edge, level: source.level || 0 }))
        .attr('fill', 'none')
        .attr('opacity', 0.8);
    }
  });

  // 创建节点 - 思维导图样式
  const nodeGroups = container.append('g')
    .attr('class', 'mind-nodes')
    .selectAll('g')
    .data(layoutedNodes)
    .enter().append('g')
    .attr('transform', d => `translate(${d.x || 0},${d.y || 0})`)
    .style('cursor', 'pointer')
    .on('click', (event, d) => {
      event.stopPropagation();
      onNodeClick?.(d);
    });

  console.log('创建节点组:', nodeGroups.size());

  // 根据层级设置不同样式
  nodeGroups.each(function(d) {
    const group = d3.select(this);
    const nodeShape = typeof mindMapStyle.nodeShape === 'function' 
      ? mindMapStyle.nodeShape(d) 
      : mindMapStyle.nodeShape || 'roundRect';
    
    // 使用节点形状渲染器
    const shapeRenderer = getNodeShapeRenderer(nodeShape, d3, container);
    if (shapeRenderer) {
      shapeRenderer(group.datum(d => ({
        ...d,
        color: mindMapStyle.nodeColor(d),
        size: mindMapStyle.nodeSize(d)
      })));
    } else {
      // 回退到简单的圆形
      group.append('circle')
        .attr('r', mindMapStyle.nodeSize(d))
        .attr('fill', mindMapStyle.nodeColor(d))
        .attr('stroke', '#fff')
        .attr('stroke-width', 2);
    }

    // 添加文本
    group.append('text')
      .text(d.label || d.name || d.id)
      .attr('text-anchor', 'middle')
      .attr('dy', '0.35em')
      .attr('fill', mindMapStyle.labelColor)
      .attr('font-size', typeof mindMapStyle.labelSize === 'function' ? mindMapStyle.labelSize(d) : mindMapStyle.labelSize)
      .attr('font-weight', (d.level === 0) ? 'bold' : 'normal');
  });
  
  console.log('思维导图节点渲染完成');
};

/**
 * 默认图谱渲染
 */
export const renderDefaultGraph = (container, nodes, edges, graphType, simulation, onNodeClick, editable, onNodePositionUpdate) => {
  const graphStyle = getGraphTypeStyle(graphType);
  
  // 初始化节点位置，避免堆叠
  nodes.forEach((node, i) => {
    if (!node.x || !node.y) {
      const angle = (i / nodes.length) * 2 * Math.PI;
      const radius = Math.min(container.attr('width'), container.attr('height')) * 0.3;
      node.x = container.attr('width') / 2 + radius * Math.cos(angle);
      node.y = container.attr('height') / 2 + radius * Math.sin(angle);
    }
  });

  // 创建连接线
  const links = container.append('g')
    .attr('class', 'graph-links')
    .selectAll('line')
    .data(edges.filter(edge => {
      // 确保源节点和目标节点都存在
      const sourceExists = nodes.some(node => node.id === (typeof edge.source === 'object' ? edge.source.id : edge.source));
      const targetExists = nodes.some(node => node.id === (typeof edge.target === 'object' ? edge.target.id : edge.target));
      return sourceExists && targetExists;
    }))
    .enter().append('line')
    .attr('stroke', d => graphStyle.edgeColor(d))
    .attr('stroke-width', d => graphStyle.edgeWidth(d))
    .attr('opacity', 0.7);

  // 创建节点
  const nodeGroups = container.append('g')
    .attr('class', 'graph-nodes')
    .selectAll('g')
    .data(nodes)
    .enter().append('g')
    .style('cursor', 'pointer')
    .call(createDragBehavior(simulation, editable, onNodePositionUpdate))
    .on('click', (event, d) => {
      event.stopPropagation();
      onNodeClick?.(d);
    });

  // 使用节点形状渲染器
  nodeGroups.each(function(d) {
    const group = d3.select(this);
    const nodeShape = typeof graphStyle.nodeShape === 'function' 
      ? graphStyle.nodeShape(d) 
      : graphStyle.nodeShape || 'circle';
    
    const shapeRenderer = getNodeShapeRenderer(nodeShape, d3, container);
    if (shapeRenderer) {
      shapeRenderer(group.datum(d => ({
        ...d,
        color: graphStyle.nodeColor(d),
        size: graphStyle.nodeSize(d)
      })));
    } else {
      // 回退到简单的圆形
      group.append('circle')
        .attr('r', graphStyle.nodeSize(d))
        .attr('fill', graphStyle.nodeColor(d))
        .attr('stroke', '#fff')
        .attr('stroke-width', 2);
    }

    // 添加文本
    group.append('text')
      .text(d.label || d.name || d.id)
      .attr('text-anchor', 'middle')
      .attr('dy', '0.35em')
      .attr('fill', graphStyle.labelColor)
      .attr('font-size', typeof graphStyle.labelSize === 'function' ? graphStyle.labelSize(d) : graphStyle.labelSize)
      .attr('font-weight', 'normal');
  });

  // 更新位置
  if (simulation) {
    simulation.on('tick', () => {
      links
        .attr('x1', d => d.source.x)
        .attr('y1', d => d.source.y)
        .attr('x2', d => d.target.x)
        .attr('y2', d => d.target.y);

      nodeGroups.attr('transform', d => `translate(${d.x},${d.y})`);
    });
  }

  return simulation;
};

// 导出其他渲染函数
export { renderConceptMap, renderFlowChart, renderSocialNetwork, renderOntologyGraph };